package site.teamo.biu.flink.web.configuration.user;

import cn.hutool.cache.Cache;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import site.teamo.biu.flink.web.controller.model.BiuJSONResult;
import site.teamo.biu.flink.web.exception.BiuResponseCode;
import site.teamo.biu.flink.web.util.BiuJSONResultUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {

    @Resource
    private Cache<String, String> session;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(UserConfiguration.TOKEN_HEADER_NAME);
        String username = session.get(token, true);
        if (StrUtil.isNotBlank(username)) {
            request.setAttribute(UserConfiguration.USERNAME_ATTRIBUTE_NAME, username);
            return true;
        }
        BiuJSONResult message = BiuJSONResultUtils.error(BiuResponseCode.LOGIN_EXPIRED);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().write(JSON.toJSONString(message));
        return false;
    }
}